package com.lianniu.web.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lianniu.redis.RedisUtils;
import com.lianniu.web.base.BaseResult;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;

public class VerifyCodeUtil {

	private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";

	private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";

	private static String URI_TPL_SEND_SMS = "http://web.amnc.net:9881/app/v1/appMain/cattleTradeSendCode?type=1&mobile=";

	private static String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";

	private static String ENCODING = "UTF-8";

	private static String LABEL = "链牛";
	
	private static String YUNPIAN_KEY = "24c9c647d4bbd29b9eb777ea8de59e69";
	
	final static Logger LOGGER = Logger.getLogger(VerifyCodeUtil.class);

	public static BaseResult sendMsg(String phone) {

		String mobile;
		String result;
		String codeUuid = UUIDUtil.getUUID();
		try {
			mobile = URLEncoder.encode(phone, ENCODING);
			result = VerifyCodeUtil.tplSendSms(mobile);
			Map<String, Object> map = new Hashtable<>();
			map.put("codeUuid", codeUuid);
			LOGGER.info(codeUuid);
			JSONObject jsonObject = JSON.parseObject(result);
			boolean isSuccess = jsonObject.getBoolean("success");
			LOGGER.info(result);
			if (isSuccess){
				String checkcode = jsonObject.getString("code");
				RedisUtils.setTimeOut("codeUuid:" + codeUuid, checkcode, 60 * 11);
				map.put("result", "发送成功！");
				return  BaseResult.success(map);
			}else {
				String msg = jsonObject.getString("submsg");
				return BaseResult.exception(msg);
			}

		} catch (UnsupportedEncodingException e1) {
			return BaseResult.exception(e1.getMessage());
		}catch (IOException e) {
			return BaseResult.exception(e.getMessage());
		}
		
		

	}

	/**
	 * 取账户信息
	 *
	 * @return json格式字符串
	 * @throws java.io.IOException
	 */

	public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("apikey", apikey);
		return post(URI_GET_USER_INFO, params);
	}

	/**
	 * 智能匹配模版接口发短信
	 *
	 * @param apikey
	 *            apikey
	 * @param text
	 *            短信内容
	 * @param mobile
	 *            接受的手机号
	 * @return json格式字符串
	 * @throws IOException
	 */

	public static String sendSms(String apikey, String text, String mobile) throws IOException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("apikey", apikey);
		params.put("text", text);
		params.put("mobile", mobile);
		return post(URI_SEND_SMS, params);
	}
	
	/**
	 * 测试发送短信
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			/*String sendSms = sendSms("7dbd34c14f546aae2dc0f0607e194188","【那山那茶】您的验证码是 1234","17686408618");
			
			System.err.println(sendSms);*/
			
			//初始化clnt,使用单例方式
			YunpianClient clnt = new YunpianClient("24c9c647d4bbd29b9eb777ea8de59e69").init();
			
			
			
			
			
			//发送短信API
			Map<String, String> param = clnt.newParam(2);
			param.put(YunpianClient.MOBILE, "17686408618");
			String code = getCode();
			param.put(YunpianClient.TEXT, "【那山那茶网】您的验证码是"+code);
			Result<SmsSingleSend> r = clnt.sms().single_send(param);
			System.err.println(r);
			SmsSingleSend data = r.getData();
			
			//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
			
			

			//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*

			//释放clnt
			clnt.close();
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 通过模板发送短信(不推荐)
	 *
	 * @param apikey
	 *            apikey
	 * @param tpl_id
	 *            模板id
	 * @param tpl_value
	 *            模板变量值
	 * @param mobile
	 *            接受的手机号
	 * @return json格式字符串
	 * @throws IOException
	 */

	public static String tplSendSms( String mobile) throws IOException {
		String url = URI_TPL_SEND_SMS+mobile;
		return post(url, null);
	}

	/**
	 * 通过接口发送语音验证码
	 * 
	 * @param apikey
	 *            apikey
	 * @param mobile
	 *            接收的手机号
	 * @param code
	 *            验证码
	 * @return
	 */

	public static String sendVoice(String apikey, String mobile, String code) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("apikey", apikey);
		params.put("mobile", mobile);
		params.put("code", code);
		return post(URI_SEND_VOICE, params);
	}

	/**
	 * 基于HttpClient 4.3的通用POST方法
	 *
	 * @param url
	 *            提交的URL
	 * @param paramsMap
	 *            提交<参数，值>Map
	 * @return 提交响应
	 */

	public static String post(String url, Map<String, String> paramsMap) {
		CloseableHttpClient client = HttpClients.createDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost method = new HttpPost(url);
			if (paramsMap != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
					paramList.add(pair);
				}
				method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
			}
			response = client.execute(method);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return responseText;
	}
	
	public static BaseResult sendMsgYun(String phone){
		String mobile;
		String codeUuid = UUIDUtil.getUUID();
		try {
			mobile = URLEncoder.encode(phone, ENCODING);
			YunpianClient clnt = null;
			try {
				clnt = new YunpianClient(YUNPIAN_KEY).init();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				return BaseResult.success();
			}
			//发送短信API
			Map<String, String> param = clnt.newParam(2);
			param.put(YunpianClient.MOBILE, mobile);
			String code = getCode();
			param.put(YunpianClient.TEXT, "【那山那茶网】您的验证码是"+code);
			Result<SmsSingleSend> r = clnt.sms().single_send(param);
			LOGGER.info(r);
			Integer flag = r.getCode();
			Map<String, Object> map = new Hashtable<>();
			map.put("codeUuid", codeUuid);
			LOGGER.info(codeUuid);
			if (flag==0){
				RedisUtils.setTimeOut("codeUuid:" + codeUuid, code, 60 * 11);
				map.put("result", "发送成功！");
				return  BaseResult.success(map);
			}else {
				return BaseResult.exception(r.getMsg());
			}
		}catch (Exception e) {
			return BaseResult.exception(e.getMessage());
		}
	}
	
	private static String getCode(){
		Random random = new Random();
		
		int nextInt = random.nextInt();
		
		System.err.println(nextInt);
		
		String code = Integer.toString(nextInt);
		
		code = code.substring(code.length()-4, code.length());
		
		System.err.println(code);
		
		return code;
	}
}
